<template>
  <div class="map-container">
    <!-- 地图容器 -->
    <div ref="chartRef" class="chart-container"></div>

    <!-- 加载状态提示（新增，提升用户体验） -->
    <div v-if="isLoading" class="loading-mask">
      <div class="spinner"></div>
      <p>地图加载中...</p>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch, nextTick } from "vue";
// 按需引入ECharts核心模块，减少打包体积
import * as echarts from "echarts/core";
import { GeoComponent, TooltipComponent } from "echarts/components";
// 导入折线图组件
import { MapChart, ScatterChart, LineChart } from "echarts/charts";
import { CanvasRenderer } from "echarts/renderers";
import { airportsApi } from "@/api/home";

// 注册所需模块（仅保留必要组件）
echarts.use([
  GeoComponent,
  MapChart,
  ScatterChart,
  LineChart,
  CanvasRenderer,
  TooltipComponent,
]);

// 组件状态
const chartRef = ref(null);
const chart = ref(null);
const isReady = ref(false);
const isLoading = ref(true); // 加载状态管理

// 地图常量配置（非响应式，减少Proxy开销）
const MAP_CONFIG = {
  center: [105, 35],
  zoom: 1.0,
  backgroundColor: "#ffffff",
  areaColor: "#e6f7ff",
  borderColor: "#91cc75",
  borderWidth: 1,
  // 修复：明确定义为经纬度数组 [经度, 纬度]
  beijingCoord: [116.4, 39.9], // 北京地理中心点坐标
};

// 异步加载地图数据（核心优化：避免阻塞主线程）
const loadMapData = async () => {
  try {
    // 动态导入JSON，避免打包到主JS
    const { default: chinaJson } = await import("@/assets/china.json");
    echarts.registerMap("china", chinaJson);
    return true;
  } catch (error) {
    console.error("地图数据加载失败:", error);
    return false;
  }
};

// 初始化图表
const initChart = () => {
  if (!isReady.value || !chart.value) return;
  const option = {
    backgroundColor: MAP_CONFIG.backgroundColor,
    tooltip: { show: false },
    geo: {
      map: "china",
      show: true,
      roam: false, // 禁止缩放平移（根据需求调整）
      center: MAP_CONFIG.center,
      zoom: MAP_CONFIG.zoom,
      label: { show: false },
      itemStyle: {
        areaColor: MAP_CONFIG.areaColor,
        borderColor: MAP_CONFIG.borderColor,
        borderWidth: MAP_CONFIG.borderWidth,
      },
    },
    series: [],
  };
  chart.value.setOption(option);

  // 调用-获取所有机场信息接口 airportsApi
  getAirportsApi();
};
// 绘制所有机场
const getAirportsApi = async () => {
  const { code, data } = await airportsApi();
  if (code === 200) {
    const newArrs = data.map((item) => ({
      name: item.city, // 取原对象的 "city" 字段作为新对象的 "name"
      value: [item.longitude, item.latitude], // 经纬度数组（注意顺序：经度在前，纬度在后）
    }));
    // 绘制机场标识
    airportCoordinates(newArrs);
  }
};
const airportCoordinates = (newArrs) => {
  const scatterSeries = {
    type: "scatter",
    coordinateSystem: "geo",
    name: "北京定位点",
    data: newArrs,
    symbol: "circle",
    symbolSize: 10,
    itemStyle: { color: "#ff4d4f", borderColor: "#fff", borderWidth: 2 },
    emphasis: { symbolSize: 12, itemStyle: { color: "#ff0000" } },
  };

  // 追加系列：仅更新series，触发散点局部渲染
  chart.value.setOption({
    series: [...chart.value.getOption().series, scatterSeries], // 保留原有series，追加新系列
  });
};

// 组件挂载时初始化
onMounted(() => {
  // 延迟初始化，优先保证页面框架渲染
  const initTimer = setTimeout(() => {
    clearTimeout(initTimer);
    nextTick(async () => {
      if (!chartRef.value) return;
      // 1. 初始化ECharts实例（轻量操作）
      chart.value = echarts.init(chartRef.value, null, {
        renderer: "canvas", // 强制使用Canvas渲染，性能更优
        useDirtyRect: true, // 启用脏矩形渲染，减少重绘区域
      });
      // 2. 异步加载地图数据
      const dataLoaded = await loadMapData();
      if (!dataLoaded) {
        isLoading.value = false;
        return;
      }
      // 3. 完成初始化
      isReady.value = true;
      initChart();
      isLoading.value = false;
    });
  }, 100); // 100ms延迟，平衡首屏速度和初始化时机
});

// 监听容器尺寸变化，自适应调整
watch(
  () => chartRef.value?.clientWidth,
  (newWidth) => {
    if (newWidth && isReady.value) {
      chart.value.resize({
        animation: { duration: 300 }, // 平滑过渡
      });
    }
  }
);

// 窗口大小变化时额外处理
const handleWindowResize = () => {
  if (isReady.value) chart.value.resize();
};

window.addEventListener("resize", handleWindowResize);

// 组件卸载时清理资源
onUnmounted(() => {
  window.removeEventListener("resize", handleWindowResize);
  if (chart.value) {
    chart.value.dispose();
    chart.value = null;
  }
  isReady.value = false;
});
</script>

<style scoped>
.map-container {
  position: relative;
  width: 100vw;
  height: 100vh;
  overflow: hidden;
}

.chart-container {
  width: 100%;
  height: 100%;
}

/* 加载状态样式（新增） */
.loading-mask {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: rgba(255, 255, 255, 0.8);
  z-index: 10;
  gap: 16px;
}

.spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #e0e0e0;
  border-top: 4px solid #42b983;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

/* 清理无用样式 */
</style>
